package com.minisoft.activity;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.Page;
import cn.hutool.db.PageResult;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.minisoft.entity.TemplateContentDto;
import com.minisoft.gateway.AutoAuthorization;
import com.minisoft.utils.excel.ExportDaasResultBuilding;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.junit.Test;

import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author JueSu
 * @description: TODO
 * @date 2022/9/19 13:10
 */
@Slf4j
public class ActivityTest {

    public static String DB_ACT = "act-pro";

    ThreadPoolExecutor poolExecutor = ThreadUtil.newExecutor(10, 10);

    private CountDownLatch latch;

    @Test
    public void sendMessage() throws Exception {
        List<String> list = FileUtil.readUtf8Lines(this.getClass().getResource("/act.txt"));
        for (String s : list) {
            String[] s1 = s.split("\t");
            String phone = s1[0];
            String code = s1[1];
            String msg = StrUtil.format("尊敬的{}用户，您好！恭喜您抽中\"迪信通600元超值大礼包\"，兑换码为：{} 复制此码，在【微信】搜索小程序“迪信通官方商城”，进入后点击右下角【我的】-【优惠券】内粘贴兑换码进行兑换使用, 请您在规定时间内领取奖品，逾期作废，祝您生活愉快！", phone.substring(7, 11), code);
            System.out.println(msg);
            JSONObject message = JSONUtil.createObj()
                    .set("message", msg)
                    .set("mobile",phone)
                    .set("createId", "活动中心");
            String result = HttpUtil.post("http://interact-center.paas.huafagroup.com/message/singleSend", message.toString());
            Console.log("{}-{}",phone,result);
        }
    }

    @Test
    public void sendWxMessage() throws Exception {
        List<String> list = FileUtil.readUtf8Lines(this.getClass().getResource("/openids.txt"));
        for (String openid : list) {
            List<TemplateContentDto> templateList = ListUtil.toList(
                    new TemplateContentDto("有新购房活动！"),
                    new TemplateContentDto("华粉walk盲盒乐游"),// "活动名称"
                    new TemplateContentDto("分享活动获取更多客户线索"),
                    new TemplateContentDto("2024年9月1日"),// "活动时间"
                    new TemplateContentDto("请分享活动给好友或朋友圈，获取更多客户线索！"));
            JSONObject miniProgram = new JSONObject();
            //pro
            miniProgram.set("appid","wx3dcdb02583414cd6")
                    .set("pagePath","src/pages/activity/pages/clock-in-place/index?id=1497");
            //sit
//            miniProgram.set("appid","wx7f25b571f08de7c2")
//                    .set("pagePath","src/pages/activity/pages/clock-in-place/index?id=1588");
            JSONObject message = JSONUtil.createObj()
                    .set("userOpenId", openid)
                    .set("templateId","xzUrkHNpZVrhPHNjLApK3G33QgSPrYkL5BIfA50-7-4")
                    .set("templateList", templateList)
                    .set("miniProgram",miniProgram)
                    .set("createId", "活动中心");
            String result = HttpUtil.post("http://interact-center.paas.huafagroup.com/message/wxTemplateSendByWxAppId?wxAppId=wxf895477b8fc20099", message.toString());
            Console.log("{}-{}",openid,result);
        }
    }

    @Test
    public void genLocationSQl() {
        String jsonData = FileUtil.readString(ExportDaasResultBuilding.class.getResource("/temp1.txt"),"utf-8");
        JSONArray jsonArray = JSONUtil.parseArray(jsonData);
        Map<String, String> map = new HashMap<>();
        for (Object o : jsonArray) {
            JSONObject jsonObject = (JSONObject) o;
            JSONArray items = jsonObject.getJSONArray("items");
            for (Object item : items) {
                JSONObject itemJson = (JSONObject) item;
                String latitude = itemJson.getStr("latitude");
                String longitude = itemJson.getStr("longitude");
                map.put(longitude + "_" + latitude, jsonObject.getStr("name") + "-" + itemJson.getStr("name"));
            }
        }
        System.out.println(map);
        ExcelReader reader = new ExcelReader("D:\\temp\\打卡活动地点.xlsx", 0);
        List<List<Object>> rows = reader.read(0);
        for (int i = 1; i < rows.size(); i++) {
            List<Object> row = rows.get(i);
            Long id = (Long) row.get(0);
            String remark = row.get(1).toString();
            String format = StrUtil.format("update promotion_activity_fission_log set avatar = '{}' where id = {};", map.get(remark), id);
            Console.log(format);
        }


    }

    @Test
    public void exportAnalysisData1() throws Exception {
        JSONObject body = JSONUtil.createObj().set("page", 1).set("size",3000);//.set("upperStatus",1);
        String s = HttpUtil.post("http://activity.paas.huafagroup.com/admin-api/v1/promotion-activity/analysis?createdBy=chenjuesu&userId=000049599", body.toString());
        JSONArray content = JSONUtil.parseObj(s).getJSONObject("data").getJSONArray("content");
        ExcelWriter writer = ExcelUtil.getWriter("C:\\Users\\31594\\Downloads\\活动中心-统计数据0109.xlsx");

        for (int i = 0; i < content.size(); i++) {

            JSONObject item = (JSONObject)content.get(i);
            Integer id = item.getInt("id");
            log.info("{}/{},actId = {}",i,content.size(),id);
            body = JSONUtil.createObj().set("id",id);
            s = HttpUtil.get("http://activity.paas.huafagroup.com/admin-api/v1/promotion-activity/getById", body);
            JSONObject data = JSONUtil.parseObj(s).getJSONObject("data");
            int rowIdx = i + 1,colIdx = 0;

            Integer projectType = data.getJSONObject("ext").getInt("projectType");
            String projectName = "",city = "",area = "";
            if (projectType != null && projectType == 2) {//全国
                projectName = "全国";
            } else {
                JSONArray projectInfoList = data.getJSONArray("projectInfoList");
                StringBuilder sb = new StringBuilder();
                for (Object o : projectInfoList) {
                    JSONObject project = (JSONObject) o;
                    if (StrUtil.isBlank(area)) {
                        area = project.getStr("areaName");
                    }
                    if (StrUtil.isBlank(city)) {
                        city = project.getStr("realCityName");
                    }
                    if (sb.length() > 0) {
                        sb.append(",");
                    }
                    sb.append(project.getStr("projectName"));
                }
                projectName = sb.toString();
            }

            writer
                    .writeCellValue(colIdx++, rowIdx, area)
                    .writeCellValue(colIdx++, rowIdx, city)
                    .writeCellValue(colIdx++, rowIdx, projectName)
                    .writeCellValue(colIdx++, rowIdx, item.get("template"))
                    .writeCellValue(colIdx++, rowIdx, item.get("activityName"))
                    .writeCellValue(colIdx++, rowIdx, data.get("startTime"))
//                    .writeCellValue(colIdx++, rowIdx, data.get("endTime"))
                    .writeCellValue(colIdx++, rowIdx, item.get("accessNumber"))
                    .writeCellValue(colIdx++, rowIdx, item.get("accessPeopleNumber"))
                    .writeCellValue(colIdx++, rowIdx, item.get("shareNumber"))
                    .writeCellValue(colIdx++, rowIdx, item.get("sharePeopleNumber"))
                    .writeCellValue(colIdx++, rowIdx, item.get("joinNumber"))
                    .writeCellValue(colIdx++, rowIdx, item.get("joinPeopleNumber"))
                    .writeCellValue(colIdx++, rowIdx, item.get("lzPeopleNumber"))
                    .writeCellValue(colIdx++, rowIdx, item.get("writeOffPeopleNumber"));
            writer.flush();
        }
        writer.close();
    }

    /**
     * 导出活动分析数据
     * @throws Exception
     */
    @Test
    public void exportAnalysisData() throws Exception {
        JSONObject body = JSONUtil.createObj().set("page", 1).set("size",5000).set("upperStatus",1);
        String s = HttpUtil.post("http://activity.paas.huafagroup.com/admin-api/v1/promotion-activity/analysis?createdBy=chenjuesu&userId=000049599", body.toString());
        JSONArray content = JSONUtil.parseObj(s).getJSONObject("data").getJSONArray("content");
        ExcelWriter writer = ExcelUtil.getWriter("C:\\Users\\31594\\Downloads\\活动中心-活动数据1220.xlsx");
        int lastId = 1140;//上次的导出id,小于它则直接完成
        for (int i = 0; i < content.size(); i++) {

            JSONObject item = (JSONObject)content.get(i);
            Integer id = item.getInt("id");
            log.info("{}/{},actId = {}",i,content.size(),id);
            if (id == lastId) {
                log.info("已到上次导出位置，退出");
                break;
            }
            body = JSONUtil.createObj().set("id",id);
            s = HttpUtil.post("http://activity.paas.huafagroup.com/admin-api/v1/promotion-activity/getAccessAndDealInfoByActivityId", body.toString());
            JSONObject data = JSONUtil.parseObj(s).getJSONObject("data");
            int rowIdx = i + 1;
            writer.writeCellValue(0, rowIdx, item.get("activityName"))
                    .writeCellValue(1, rowIdx, item.get("template"))
                    .writeCellValue(2, rowIdx, item.get("accessNumber"))
                    .writeCellValue(3, rowIdx, item.get("accessPeopleNumber"))
                    .writeCellValue(4, rowIdx, item.get("shareNumber"))
                    .writeCellValue(5, rowIdx, item.get("sharePeopleNumber"))
                    .writeCellValue(6, rowIdx, item.get("joinNumber"))
                    .writeCellValue(7, rowIdx, item.get("joinPeopleNumber"))
                    .writeCellValue(8, rowIdx, item.get("lzPeopleNumber"))
                    .writeCellValue(9, rowIdx, item.get("lzRate"))
                    .writeCellValue(10, rowIdx, item.get("writeOffPeopleNumber"))
                    .writeCellValue(11, rowIdx, data.get("visitPeopleNumber"))
                    .writeCellValue(12, rowIdx, data.get("dealPeopleNumber"))
                    .writeCellValue(13, rowIdx, data.get("goVisitPeopleNumber"))
                    .writeCellValue(14, rowIdx, data.get("goDealPeopleNumber"))
                    .writeCellValue(15, rowIdx, data.get("startTime"));
            writer.flush();
        }
        writer.close();
    }


    @Test
    public void fillData() throws Exception {
        List<Entity> list = Db.use(DB_ACT).query("select * from promotion_activity a where a.upper_status  = 1 and is_deleted = 0 and a.created_time > '2021-01-01'");
        Map<String, Long> name2Id = new HashMap<>();
        list.forEach(item -> name2Id.put(item.getStr("name"), item.getLong("id")));
        long start = System.currentTimeMillis();

        ExcelWriter writer = ExcelUtil.getWriter("C:\\Users\\31594\\Downloads\\活动中心-活动数据.xlsx");
        latch = new CountDownLatch(writer.getRowCount() - 1);

        for (int i = 1; i < writer.getRowCount(); i++) {
            String actName = writer.getCell(0, i).getStringCellValue();
            Cell cell = writer.getCell(15, i);
            //通过名称获取活动id，调用接口获取数据
            Long id = name2Id.get(actName);
            if (cell != null) {
                log.error("无法获取到活动id或已处理，跳过 {}", actName);
                latch.countDown();
                continue;
            }
            poolExecutor.execute(new TaskRunner(id,writer,i));
        }
        log.info("等待刷数完成。。。。");
        latch.await();
        log.info("刷数据完成，耗时{}秒", (System.currentTimeMillis() - start) / 1000);
        writer.flush();
        writer.close();
    }

    class TaskRunner implements Runnable {

        private Long id;
        ExcelWriter writer;
        int i;

        public TaskRunner(Long id, ExcelWriter writer, int i) {
            this.id = id;
            this.i = i;
            this.writer = writer;
        }

        @SneakyThrows
        public void run() {
            Console.log("执行中：{}-{}", i,id);
            JSONObject body = JSONUtil.createObj().set("id", id);
            try {
//                String post = HttpUtil.post("http://activity.paas.huafagroup.com/admin-api/v1/promotion-activity/analysisDetail", body.toString());
                String post = HttpUtil.post("http://activity.paas.huafagroup.com/admin-api/v1/promotion-activity/getAccessAndDealInfoByActivityId", body.toString());
                log.info(post);
                JSONObject data = JSONUtil.parseObj(post).getJSONObject("data");

                writer.writeCellValue(11, i, data.get("visitPeopleNumber")).writeCellValue(12, i, data.get("dealPeopleNumber")).writeCellValue(13, i, data.get("goVisitPeopleNumber")).writeCellValue(14, i, data.get("goDealPeopleNumber"))
                        .writeCellValue(15, i, data.get("startTime"));
                writer.flush();
            } catch (Exception e) {
                log.error("error,",e);
            }
            latch.countDown();
        }

    }


    /**
     * 补发红包
     *
     * @throws SQLException
     */
    @Test
    public void sendRedPack() throws SQLException {

        int activityId = 1314;
        String appId = "wx9d9b71536d69f6ba";
        String url = "http://basepay.paas.huafagroup.com/v1/transaction-api/transfer";

        Entity activity = Db.use(DB_ACT).queryOne("select * from promotion_activity r where r.id = ?", activityId);
        //根据活动id找到发送失败的订单
        List<Entity> list = Db.use(DB_ACT).query("select * from promotion_activity_order o where o.activity_id  = ? and o.status = 2", activityId);
        Console.log("find records {}", list.size());
        //根据resource_id找到发送金额
        for (int i = 0; i < list.size(); i++) {
            Entity order = list.get(i);
            Long id = order.getLong("id");
            Long resource_id = order.getLong("resource_id");
            Entity res = Db.use(DB_ACT).queryOne("select * from promotion_his_resource r where r.id = ?", resource_id);
            int amount = (int) (res.getDouble("coupon_value") * 100);
            //发送红包
            JSONObject data = new JSONObject();

            String projectId = res.getStr("project_id");
            String bizOrderNo = order.getStr("code");
            data.set("amount", amount).set("sendName", "华发置业通").set("openid", order.getStr("user_id")).set("description", "活动激励")
                    .set("wishing", "恭喜发财").set("actName", activity.getStr("name")).set("appId", appId).set("projectId", projectId).set("bizOrderNo", bizOrderNo);

            Console.log("send data {}", data);
            String post = HttpUtil.post(url, data.toString());
            Console.log("post result {}", post);

            //修改订单状态status=1
            int update = Db.use(DB_ACT).execute("update promotion_activity_order set status = 1 where id = ?", id);
            Console.log("update order {} count {}", id, update);

            //修改核销表状态 verify_status = 1
            update = Db.use(DB_ACT).execute("update promotion_activity_verify set verify_status = 1 where order_id = ?", id);
            Console.log("update promotion_activity_verify {} count {}", id, update);

            Console.log("finish {} order", i);
        }
    }

    /**
     * 补发红包V2
     *
     * @throws SQLException
     */
    @Test
    public void sendRedPackUsingLog() throws SQLException {

        int activityId = 1314;

        //根据活动id找到发送失败的
        List<Entity> list = Db.use(DB_ACT).query("select * from promotion_external_service_log where activity_id = ? and is_deleted = 0", activityId);
        Console.log("find records {}", list.size());
        int si = 1,ss = 1,payTotal = 0;
        //根据resource_id找到发送金额
        for (int i = 0; i < list.size(); i++) {
            Entity log = list.get(i);
            String response_json = log.getStr("response_json");
            if (response_json.contains("账户余额不足")) {
                JSONObject request_json = JSONUtil.parseObj(log.getStr("request_json"));
                Entity order = Db.use(DB_ACT).queryOne("select * from promotion_activity_order where code = ?", request_json.getStr("bizOrderNo"));
                if (order.getInt("status") == 1) {
                    Console.log("{}. 订单 {} 已经更新成功，跳过。",si++,request_json.getStr("bizOrderNo"));
                    continue;
                }
                //发送红包
                Console.log("send data {}", log.getStr("request_json"));
                String post = HttpUtil.post(log.getStr("url"), log.getStr("request_json"));
                Console.log("post result {}", post);

                //修改日志状态
                JSONObject postResult = JSONUtil.parseObj(post);
                if (postResult.getInt("code") == 200) {

                    int update = Db.use(DB_ACT).execute("update promotion_external_service_log set is_deleted = 1 where id = ?", log.getLong("id"));
                    Console.log("update log {} count {}", log.getLong("id"), update);

                    int orderId = order.getInt("id");

                    //修改订单状态status=1
                    update = Db.use(DB_ACT).execute("update promotion_activity_order set status = 1 where id = ?", orderId);
                    Console.log("update order {} count {}", orderId, update);

                    //修改核销表状态 verify_status = 1
                    update = Db.use(DB_ACT).execute("update promotion_activity_verify set verify_status = 1 where order_id = ?", orderId);
                    Console.log("update promotion_activity_verify {} count {}", orderId, update);

                    Console.log("{}. finish {} order",ss++, i);
                    payTotal += request_json.getInt("amount");
                }
            }
        }
        Console.log("finished ,payed {} ",payTotal);

    }

    @Test
    public void updateProjectName() throws SQLException, IOException {
        List<String> activityNames = FileUtil.readUtf8Lines(getClass().getResource("/activityNames.txt"));
        List<Entity> list = Db.use(DB_ACT).find(Entity.create("promotion_activity").set("name", activityNames));
        List<Integer> idList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Entity activity = list.get(i);
            Integer id = activity.getInt("id");
            idList.add(id);
        }

        ExcelReader reader = ExcelUtil.getReader("C:\\Users\\31594\\IdeaProjects\\workUtils\\src\\main\\resources\\各项目的新推广名.xlsx");
        List<Map<String, Object>> records = reader.readAll();
        List<String> sqlList = new ArrayList<>();
        for (int i = 0; i < records.size(); i++) {
            Map<String, Object> record = records.get(i);
            Object city = record.get("城市");
            Object oldName = record.get("营销系统项目名");
            Object newName = record.get("新名字");
            String sql = StrUtil.format("update promotion_activity_participation set project_name = '{}' where activity_id in ({}) and project_name = '{}' and real_city_name = '{}';", newName, CollUtil.join(idList, ","), oldName, city);
            sqlList.add(sql);
        }
        sqlList.forEach(System.out::println);
//        Db.use(DB_ACT).executeBatch()

        //刷新缓存
//        "http://activity.paas.huafagroup.com/admin-api/v1/cache/updateCacheActInfo";

    }
}
